<template>

    <div class="app-content">
        <el-card class="search-card" shadow="never">
            <!-- 搜索部分 -->
            <el-row :gutter="10" class="search-section">
                <el-col :span="7">
                    <el-form-item label="所属租户：">
                        <el-select v-model="searchData.tenantIdList" multiple filterable clearable placeholder="选择租户"
                            style="width: 240px">
                            <el-option v-for="tenant in allDeptInfo" :key="tenant" :label="tenant.tenantName"
                                :value="tenant.tenantId" />
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="5">
                    <el-form-item label="发布人：">
                        <el-input v-model="searchData.pulishName" placeholder="请输入用户名"></el-input>
                    </el-form-item>
                </el-col>

                <el-col :span="5">
                    <el-form-item label="通知类型">
                        <el-select v-model="searchData.noticeType" placeholder="请选择通知类型">
                            <el-option label="邀请信息" value="1"></el-option>
                            <el-option label="通知公告" value="0"></el-option>
                        </el-select>
                    </el-form-item>
                </el-col>

            </el-row>
            <el-row :gutter="10" class="search-section2">
                <el-col :span="9">
                    <el-form-item label="发布时间：">
                        <div class="block">
                            <el-date-picker v-model="searchData.createTimeList" type="daterange" unlink-panels
                                range-separator=">>" start-placeholder="开始日期" end-placeholder="结束日期"
                                :shortcuts="shortcuts" />
                        </div>

                    </el-form-item>

                </el-col>
                <el-col :span="5">
                    <el-button type="primary" class="action-button" @click="search" :icon="Search">搜索</el-button>
                    <el-button @click="reset" type="primary" class="action-button" :icon="Refresh">重置</el-button>
                </el-col>
            </el-row>
        </el-card>
        <el-card class="search-card" shadow="never" style="margin-top: 10px;">
            <!-- 操作按钮组 -->
            <div class="button-group">
                <el-button v-role="['ROLE_admin', 'ROLE_super']" class="action-button" type="primary" :icon="Edit"
                    @click="handleAdd">发布通知</el-button>
                <el-button class="action-button" type="primary" :icon="Download" @click="handleExport">导出</el-button>
            </div>


            <!-- 数据表格 -->
            <el-table ref="tableRef" :data="tableData" style="width: 100%">
                <el-table-column prop="noticeTitle" label="标题" width="300" />
                <el-table-column prop="pulishName" label="发布人" width="100" />
                <el-table-column prop="noticeType" label="类型" width="100">
                    <template #default="scope">
                        {{ getGenderText(scope.row.noticeType) }}
                    </template>
                </el-table-column>
                <el-table-column prop="priority" label="优先级" width="100">
                    <template #default="scope">
                        {{ getPriorityText(scope.row.priority) }}
                    </template>
                </el-table-column>
                <el-table-column prop="createTime" label="创建时间" width="220">
                    <template #default="scope">
                        {{ scope.row.createTime.replace(/T/, ' ') }}
                    </template>
                </el-table-column>

                <!-- 操作列 -->
                <el-table-column label="操作">
                    <template #default="scope">
                        <el-button  class="table-button" text type="primary" :icon="EditPen" @click="handleEdit(scope.$index, scope.row)">详情</el-button>
                        <el-button v-if="scope.row.noticeType == '1'" class="table-button" text type="primary" :icon="Promotion" @click="handleAccept(scope.row)">接受</el-button>
                        <el-button v-if="scope.row.noticeType == '1'" class="table-button" text type="primary" :icon="CircleCloseFilled" @click="handleReject(scope.row)">拒绝</el-button>
                        <el-button v-else class="table-button" text type="primary" :icon="Delete"  @click="handleRowDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination class="pagination-fixed" @size-change="handleSizeChange"
                    @current-change="handleCurrentChange" :current-page="pagination.currentPage"
                    :page-sizes="[10, 15, 20, 25, 30]" :page-size="pagination.pageSize"
                    layout="total, sizes, prev, pager, next" :total="pagination.totalNum">

                </el-pagination>
            </div>
        </el-card>
        <!-- 对话框 -->
        <el-dialog v-model="dialogVisible" :title="dialogTitle" width="980" :before-close="handleClose" @open="onOpen"
            @close="onClose" append-to-body :close-on-click-modal="false" :close-on-press-escape="false">

            <template #footer>
                <div class="dialog-footer">
                    <el-button class="action-button" type="info" @click="dialogVisible = false">取消</el-button>
                    <el-button class="action-button" type="primary" @click="update()">
                        确认
                    </el-button>
                </div>
            </template>
            <el-form ref="dialogForm" style="width: 94%; margin-left: 30px;" :model="userForm" :rules="rules"
                label-width="auto" class="el-form" status-icon>

                <div v-show="segmentValue === 'basic'">
                    <el-form-item label="通知标题" prop="noticeTitle">
                        <el-input v-model="userForm.noticeTitle" style="width: 500px;" />
                    </el-form-item>
                    <el-form-item label="通知内容" prop="content" required>
                        <vditor height="200px" v-model="userForm.content" />
                    </el-form-item>
                    <el-form-item label="通知类型" prop="noticeType">
                        <el-radio-group v-model="userForm.noticeType" style="width: 200px;">
                            <el-radio value="0">通知公告</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="优先级" prop="priority">
                        <el-radio-group v-model="userForm.priority" style="width: 200px;">
                            <el-radio value="0">低</el-radio>
                            <el-radio value="1">中</el-radio>
                            <el-radio value="2">高</el-radio>
                        </el-radio-group>
                    </el-form-item>
                    <el-form-item label="备注" prop="remark" v-show="dialogType == true">
                        <el-input v-model="userForm.remark" style="width: 200px;" />
                    </el-form-item>
                    <el-form-item label="所属租户：" v-show="dialogType == true" required>
                        <el-select v-model="userForm.tenantId" filterable clearable placeholder="选择租户"
                            style="width: 240px">
                            <el-option v-for="tenant in allDeptInfo" :key="tenant" :label="tenant.tenantName"
                                :value="tenant.tenantId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属项目：" v-show="dialogType == true" required>
                        <el-select v-model="userForm.projectId" filterable clearable placeholder="选择项目"
                            style="width: 240px">
                            <el-option v-for="project in allProjectInfo" :key="project" :label="project.projectName"
                                :value="project.projectId" />
                        </el-select>
                    </el-form-item>
                    <el-form-item label="所属租户：" prop="tenantName" v-show="dialogType == false">
                        <el-input v-model="userForm.tenantName" style="width: 200px;" readonly />
                    </el-form-item>
                    <el-form-item label="所属项目：" prop="projectId" v-show="dialogType == false">
                        <el-input v-model="userForm.projectId" style="width: 200px;" readonly />
                    </el-form-item>
                    <el-form-item label="发布人：" prop="pulishName" v-show="dialogType == false">
                        <el-input v-model="userForm.pulishName" style="width: 200px;" readonly />
                    </el-form-item>
                    <!-- 通过使用 v-if，可以确保当 userForm.invitation 为 null 时，相关的表单项不会被渲染，从而避免编译器在绑定 v-model 时认为可能存在不可赋值的情况。 -->
                    <el-form-item label="邀请状态" v-if="dialogType === false && userForm.invitation">
                        <el-radio-group v-model="userForm.invitation.status" style="width: 300px;" >
                            <el-radio value="0">未处理</el-radio>
                            <el-radio value="1">已接受</el-radio>
                            <el-radio value="2">已拒绝</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </div>

            </el-form>

        </el-dialog>
    </div>
</template>
<script lang="ts" setup>
import { ref, watch, reactive } from 'vue'
import type { User } from '../../type/User';
import type { PaginationData } from '../../type/PaginationData';
import { ElMessage, ElMessageBox, FormInstance, FormRules } from 'element-plus';
import { Delete, Edit, Search, Download, Refresh, EditPen,Promotion,CircleCloseFilled } from '@element-plus/icons-vue'
import { getAllTenantInfo, findById } from '../../api/Tenant/tenantApi';
import { Tenant } from '../../type/Tenant';
import { NoticeDTO } from '../../type/Notice';
import { Project } from '../../type/Project';
import { findProjectById, getProjectList } from '../../api/Tenant/projectApi';
import { getNoticeInfo, searchNoticeInfo, publishNotice, exportNoticeInfo, deleteNotice } from '../../api/Tenant/NoticeApi';
import Vditor from '../../components/Tenant/Vditor.vue';
import { acceptInvitationMethod, rejectInvitationMethod } from '../../api/Tenant/invitationApi';
// 表格数据
const tableData = ref<NoticeDTO[]>([]);
//查询数据
const searchData = ref({
    pulishName: "",
    noticeType: "",
    createTimeList: [],
    tenantIdList: [] as string[]
});
const userForm = ref<NoticeDTO>({})

//分页
const isSearch = ref(false); // 判断是否为搜索状态

const pagination = ref<PaginationData<User>>({
    currentPage: 1,
    pageSize: 10,
    totalNum: 10,
    isMore: 0,
    totalPage: 0,
    startIndex: 0,
    items: []
});
//当每页条数发生了变化，调用此函数
const handleSizeChange = async (val: number) => {
    pagination.value.pageSize = val;
    pagination.value.currentPage = 1; // 切换每页条数时重置为第一页
    if (isSearch.value) {
        await search();  // 如果是搜索状态，调用搜索
    } else {
        await getNoticeData();  // 否则调用常规获取数据
    }
};
//当前页码发生变化，调用此函数
const handleCurrentChange = async (val: number) => {
    pagination.value.currentPage = val;
    if (isSearch.value) {
        await search();  // 如果是搜索状态，调用搜索
    } else {
        await getNoticeData();  // 否则调用常规获取数据
    }
};

// ---------------------
// 获取用户数据
const getNoticeData = async () => {

    const res = await getNoticeInfo(pagination.value?.currentPage, pagination.value?.pageSize);
    const data = res;

    // 更新表格数据
    tableData.value = data.items;

    // 更新分页信息
    pagination.value.currentPage = data.currentPage;
    pagination.value.pageSize = data.pageSize;
    pagination.value.totalNum = data.totalNum;
    pagination.value.isMore = data.isMore;
    pagination.value.totalPage = data.totalPage;
    pagination.value.startIndex = data.startIndex;

}
getNoticeData();


const allDeptInfo = ref<Tenant[]>()
const allProjectInfo = ref<Project[]>()
//获取租户数据
const getTenantData = async () => {
    const res = await getAllTenantInfo();
    allDeptInfo.value = res;
}

getTenantData();
//获取项目数据
//如果tenantIdList有值的话，就根据租户id查询项目
const getProjectData = async () => {
    if (userForm.value.tenantId) {
        const res = await findProjectById([userForm.value.tenantId]);
        allProjectInfo.value = res;
    } else {
        const res = await getProjectList();
        allProjectInfo.value = res;
    }
}
getProjectData();
//使用 watch 来监听 searchData.tenantIdList 的变化
watch(
    () => userForm.value.tenantId,
    () => {
        // 当 tenantIdList 发生变化时，重新获取项目数据
        getProjectData();
    }
);

// 获取性别的中文表示
const getGenderText = (gender: string): string => {
    switch (gender) {
        case "1":
            return '邀请信息';
        case "0":
            return '通知公告';
        default:
            return '通知公告';
    }
};

const getPriorityText = (priority: string): string => {
    switch (priority) {
        case "0":
            return '低';
        case "1":
            return '中';
        case "2":
            return '高';
        default:
            return '通知公告';
    }
};

//日期选择器
const shortcuts = [
    {
        text: 'Last week',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
        },
    },
    {
        text: 'Last month',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
        },
    },
    {
        text: 'Last 3 months',
        value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
        },
    },
]


//------------搜索----------------
const search = async () => {
    isSearch.value = true;
    const res = await searchNoticeInfo(pagination.value.currentPage, pagination.value.pageSize, searchData.value);

    // 更新表格数据
    tableData.value = res.items;

    // 更新分页信息
    pagination.value.currentPage = res.currentPage;
    pagination.value.pageSize = res.pageSize;
    pagination.value.totalNum = res.totalNum;
    pagination.value.isMore = res.isMore;
    pagination.value.totalPage = res.totalPage;
    pagination.value.startIndex = res.startIndex;
}
const reset = async () => {
    isSearch.value = false;
    searchData.value.pulishName = "";
    searchData.value.noticeType = "";
    searchData.value.createTimeList = [];
    searchData.value.tenantIdList = [];
    await getNoticeData();
}

// 处理顶部按钮操作
const handleAdd = async () => {
    //await publishNotice(userForm.value);
    dialogTitle.value = '发布通知'
    dialogVisible.value = true
    // 重置表单
    userForm.value = {}
    userForm.value.noticeType = "0";
    // 重置验证规则，避免触发验证 需要用setTimeout包裹
    setTimeout(() => {
        dialogForm.value?.clearValidate()
    }, 100)
    dialogType.value = true

}


//----------导入部分--------
const handleExport = async () => {
    // 在此添加导出操作的逻辑
    await exportNoticeInfo();
}


//------------对话框----------------
const dialogVisible = ref(false)
// 在编辑的时候不可以选择租户dialogType:false，新增的时候可以选择租户 dialogType:true
const dialogType = ref(true)
const emit = defineEmits(['dialogUpdated']);
const onOpen = () => {
    emit('dialogUpdated', dialogVisible.value)
}
const onClose = () => {
    emit('dialogUpdated', dialogVisible.value)
}
const dialogTitle = ref('')
const handleClose = (done: () => void) => {
    dialogVisible.value = false
    // 重置验证规则，避免触发验证 需要用setTimeout包裹
    setTimeout(() => {
        dialogForm.value?.clearValidate()
    }, 100)
    done()
}
const segmentValue = ref('basic')


const dialogForm = ref<FormInstance>()

const rules = reactive<FormRules<NoticeDTO>>({
    tenantId: [
        { required: true, message: '请选择租户', trigger: 'blur' },
    ],
    projectId: [
        { required: true, message: '请选择项目', trigger: 'blur' },
    ],
    content: [
        { required: true, message: '请输入通知内容', trigger: 'blur' },
    ],
    noticeTitle: [
        { required: true, message: '请输入通知标题', trigger: 'blur' },
    ]
});

// 编辑行的处理函数
const handleEdit = async (index: number, row: NoticeDTO) => {
    // 编辑逻辑
    dialogTitle.value = '查看通知详情'
    dialogType.value = false


    userForm.value = row
    const tenant = await findById(row.tenantId || "");
    if (tenant) {
        userForm.value.tenantName = tenant.tenantName;
        //console.log('tenant', tenant)
    }
    dialogVisible.value = true
};
const update = async () => {
    // 更新逻辑
    try {
        const valid = await dialogForm.value?.validate();
        if (valid) {
            if (dialogType.value === false) {
                //不更新
                dialogVisible.value = false;
            } else {
                // 新增逻辑
                // 验证租户是否选择
                if (!userForm.value.tenantId) {
                    ElMessage.error('请选择租户');
                    return;
                }
                await publishNotice(userForm.value);
                await getNoticeData();
                dialogVisible.value = false;
                ElMessage.success('发布成功！');
            }

        } else {
            // 验证失败的情况下，显示错误信息
            ElMessage.error('请检查输入项');
        }
    } catch (error) {
        // 捕获验证失败时的错误
        ElMessage.error('验证失败，请检查输入项');

    }
}

// 删除行的处理函数
const handleRowDelete = (index: number, row: NoticeDTO) => {

    ElMessageBox.confirm(`确定删除 ${row.noticeTitle} 吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
    })
        .then(async () => {
            tableData.value.splice(index, 1);
            await deleteNotice(row);
            ElMessage.success('删除成功');
            await getNoticeData();
        })
        .catch(() => {
            ElMessage.info('已取消删除');
        });
};
// 处理接受邀请
const handleAccept = async (notice: NoticeDTO) => {
    try {
        const response = await acceptInvitationMethod(notice.invitation?.token || '');
        ElMessage.success('邀请已接受，已加入项目。');
        await getNoticeData();
    } catch (error) {

    }
};

// 处理拒绝邀请
const handleReject = async (notice: NoticeDTO) => {
    try {
        const response = await rejectInvitationMethod(notice.invitation?.token || '');
        ElMessage.success('邀请已拒绝。');
        await getNoticeData();
    } catch (error) {

    }
};


</script>
<style lang="scss" scoped>
@use "sass:color";
$primary-color: #6067eb;
$info-color: #dadcf6;
$button-border-radius: 4px;
$button-padding: 0.5rem 1rem;
$button-font-size: 16px;
$color-hover: color.adjust($primary-color, $lightness: -10%); // 悬浮时的颜色
$color-disabled: color.adjust($primary-color, $lightness: 15%); // 禁用时的颜色
$info-color-hover: color.adjust($info-color, $lightness: -25%); // 悬浮时的颜色

/* 定义一个 mixin 用于公共按钮样式 */
@mixin action-button-style {
    border-radius: $button-border-radius;
    padding: $button-padding;
    font-size: $button-font-size;
    cursor: pointer;
    transition: background-color 0.3s ease, border-color 0.3s ease, color 0.3s ease;

    /* 覆盖 Element Plus 的 primary 按钮样式 */
    &.el-button--primary {
        background-color: $primary-color;
        border-color: $primary-color;
        color: #fff;

        &:hover,
        &:focus {
            background-color: $color-hover;
            border-color: $color-hover;
            color: #fff;
        }

        &.is-disabled {
            background-color: $color-disabled;
            border-color: $color-disabled;
            color: #fff;
            cursor: not-allowed;
            opacity: 1; // 确保颜色不被 Element Plus 默认的透明度覆盖
        }
    }

    &.el-button--info {
        background-color: $info-color;
        border-color: $info-color;
        color: #fff;

        &:hover,
        &:focus {
            background-color: $info-color-hover;
            border-color: $info-color-hover;
            color: #fff;
        }

        &.is-disabled {
            background-color: $color-disabled;
            border-color: $color-disabled;
            color: #fff;
            cursor: not-allowed;
            opacity: 1; // 确保颜色不被 Element Plus 默认的透明度覆盖
        }
    }

    /* 禁用状态下的样式（针对所有类型的按钮） */
    &:disabled,
    &.is-disabled {
        background-color: $color-disabled;
        border-color: $color-disabled;
        color: #fff;
        cursor: not-allowed;
        opacity: 1; // 覆盖 Element Plus 默认的透明度
    }


}

.action-button {
    @include action-button-style;
}

/* 按钮组样式 */
.button-group {
    display: flex;
    gap: 1rem;
    margin-bottom: 10px;
}

.table-button {
    color: #7e63cd;
    font-size: 14px;
    /* 设置你想要的字体大小 */
    font-weight: bold;
    /* 设置字体加粗 */
}


.search-card {
    border-radius: 10px;

    .block {
        padding: 0px 0;
        text-align: center;
        border-right: solid 1px var(--el-border-color);
        flex: 1;
    }

    .block:last-child {
        border-right: none;
    }

}


.pagination-container {
    display: flex;
    margin-top: 25px;
    justify-content: right;
    width: 100%;
    z-index: 1000;
}

.el-segmented {
    --el-segmented-item-selected-color: var(--el-text-color-primary);
    --el-segmented-item-selected-bg-color: #868cf4;
    --el-border-radius-base: 8px;
    --el-text-color-primary: #fff;
    --el-segmented-item-hover-bg-color: #b2b5f0;
    display: flex;
    justify-content: flex-start;
    /* 左对齐 */
    width: 300px;
    margin-bottom: 20px;
}
</style>